package sample;


import java.net.InetAddress;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.Scheduler;
import io.reactivex.disposables.Disposable;
import io.reactivex.rxjavafx.schedulers.JavaFxScheduler;
import io.reactivex.schedulers.Schedulers;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.TextArea;
import javafx.scene.control.cell.PropertyValueFactory;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.progress.ProgressMonitor;
import net.lingala.zip4j.util.Zip4jConstants;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.concurrent.WorkerStateEvent;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.geometry.*;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.*;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.ScrollPane;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.stage.*;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.dom4j.*;
import org.dom4j.io.SAXReader;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.net.MalformedURLException;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.logging.Logger;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


import freeseawind.ninepatch.javafx.FxNinePatch;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.Image;
import javafx.stage.Stage;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.FileHeader;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;

import static java.lang.Runtime.*;


public class Main extends Application {
    /*  Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));*/
    String openFile;
    String unZipPath;  //选择的解压文件目录
    String unZipDestPath;  //选择的存放解压文件目录

    String downloadThemeName = null;//要下载的主题名称；
    String themeAction = null;
    String globalThemeName = null;//打开当前展示预览图的主题

    private ArrayList<File> temp;
    VBox totalVbox = new VBox();    //全局     (actionHbox, threeHbox)
    HBox actionHbox = new HBox();     //操作  (openButton)
    VBox previewVbox = new VBox();     //预览图
    HBox threeHbox = new HBox();
    Pane preview_dialerPane = new Pane();
    Pane preview_messagePane = new Pane();
    Pane preview_deskPane = new Pane();
    HBox dialerVbox = new HBox();
    HBox messageVbox = new HBox();
    VBox deskVbox = new VBox();
    Pane threePane = new Pane();

    /* 拨号盘*/
    ScrollPane dialerScrollPane = new ScrollPane();
    GridPane dialerPane = new GridPane();

    GridPane realDialerPane = new GridPane();

    ImageView dialerMainBG = new ImageView();

    /* 信息界面*/
    //  VBox messageVbox = new VBox();    //联系人
    GridPane temp_messagePane = new GridPane();
    GridPane realMessagePane = new GridPane();

    /*桌面*/
    //  VBox deskVbox = new VBox();      /*桌面*/
    GridPane realDeskPane = new GridPane();

    String path = null;
    String FileName = null;
    DirectoryChooser chooser = null;
    DirectoryChooserBuilder builder = null;
    String cwd = null;
    File testFile = null;
    File file = null;
    File chosenDir = null;
    String resPathName = null;
    String colorPath = null;


    int viewCount = 0;
    Text text = new Text("");
    File[] tempList;
    Stage dialogStage = new Stage();
    ProgressIndicator progressIndicator;

    boolean loadingFlag = false;

    /*厂商tab*/
    TabPane tabPane = new TabPane();
    /*主题列表面板*/
    FlowPane themeFlow = new FlowPane();
    ScrollPane themeScroll = new ScrollPane();
    VBox themeVbox = new VBox();
    VBox factoryVbox = new VBox();


    /*主题列表显示表单*/
    TableView themesTable = new TableView();
    TableColumn firstNameCol = new TableColumn("主题ID");
    TableColumn secondNameCol = new TableColumn("主题名称");
    TableColumn lastNameCol = new TableColumn("主题预览图");


    @Override
    public void start(Stage primaryStage) throws Exception {

        /*厂商按钮 tab 显示所有厂商*/

        /*更换分栏 清空之前的数据*/
        tabPane.getTabs().clear();
        /* themeVbox.getChildren().clear();*/
        // themeFlow.getChildren().clear();
        MenuBar factory_menuBarTop = new MenuBar();
        factory_menuBarTop.prefWidthProperty().bind(primaryStage.widthProperty());
        // menuBarTop.setPrefWidth(1000);
        Menu fileMenu = new Menu("文件");
        MenuItem themeMenuItem = new MenuItem("打开主题工具");
        MenuItem refreshItem = new MenuItem("刷新");
        MenuItem exitMenuItem = new MenuItem("退出");
        exitMenuItem.setOnAction(actionEvent -> Platform.exit());
        fileMenu.getItems().addAll(themeMenuItem, refreshItem, new SeparatorMenuItem(), exitMenuItem);
        factory_menuBarTop.getMenus().addAll(fileMenu);

        /*刷新*/
        refreshItem.setOnAction(refresh -> {
            /*重新加载布局*/
            refresh(primaryStage);
           /* tabPane.getTabs().clear();
            try {
                System.err.println(Httpmethod.getFactorys());
                String jsonResult = Httpmethod.getFactorys();
                JSONArray jsonArray = JSONArray.fromObject(jsonResult);

                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                    System.err.println("获取的厂商名为》》》" + " " + jsonObject.getString("name"));
                    String factoryName = jsonObject.getString("name");
                    Tab tab = new Tab();
                    tab.setText(factoryName);
                    tab.setOnSelectionChanged(select -> {
                        HashMap map = new HashMap();
                        map.put("factoryName", tab.getText());
                        try {
                            *//*更换厂商 清空表格数据*//*
                            //   themesTable.getItems().clear();
                            themeFlow.getChildren().clear();
                            *//*请求主题数据*//*
                            String themes = Httpmethod.getThemeByFactory(map, "UTF-8");
                            JSONArray themesJson = JSONArray.fromObject(themes);

                            for (int j = 0; j < themesJson.size(); j++) {
                                VBox flow_themeVbox = new VBox();
                                flow_themeVbox.setSpacing(10);
                                HBox flow_themeHbox = new HBox();
                                flow_themeHbox.setAlignment(Pos.CENTER);
                                flow_themeHbox.setSpacing(10);
                                Hyperlink flow_themeLink = new Hyperlink();

                                JSONObject themeObject = (JSONObject) themesJson.get(j);
                                System.err.println("主题为》》》》。" + themeObject.getString("name") + " " + themeObject.getString("preview"));

                                Button flow_actionBtn = new Button();
                                Button  flow_fileBtn=new Button("目录");
                                *//*判断主题状态 按钮显示1.下载 2.解压 3. 显示*//*
                                String themeStatus = judgeThemeStatus(themeObject.getString("name"));
                                if ("下载".equals(themeStatus)) {
                                    flow_actionBtn.setText("下载");

                                    flow_themeHbox.getChildren().setAll(flow_themeLink, flow_actionBtn);
                                }
                                if ("解压".equals(themeStatus)) {
                                    flow_actionBtn.setText("解压");
                                    flow_themeHbox.getChildren().setAll(flow_themeLink, flow_actionBtn,flow_fileBtn);

                                }
                                if ("查看".equals(themeStatus)) {
                                    flow_actionBtn.setText("查看");

                                    flow_themeHbox.getChildren().setAll(flow_themeLink, flow_actionBtn,flow_fileBtn);
                                }

                                HashMap previewMap = new HashMap();
                                previewMap.put("themeName", themeObject.getString("name"));
                                ImageView preview = Httpmethod.getPreviewByTheme(previewMap, "UTF-8");
                                preview.setFitWidth(180);
                                preview.setPreserveRatio(true);

                                *//*点击列表项链接，创建新窗口显示详情主题*//*

                                flow_themeLink.setText(themeObject.getString("name"));

                                flow_themeLink.setOnAction((ActionEvent e) -> {
                                    System.out.println("This link is clicked");
                                    try {
                                        themeDetail(flow_themeLink.getText(), primaryStage);
                                    } catch (Exception e1) {
                                        e1.printStackTrace();
                                    }

                                });

                                preview.setOnMouseClicked(clicked -> {
                                    System.out.println("This link is clicked");
                                    try {
                                        themeDetail(flow_themeLink.getText(), primaryStage);
                                    } catch (Exception e1) {
                                        e1.printStackTrace();
                                    }
                                });


                                *//*操作按钮*//*
                                flow_actionBtn.setOnAction(download -> {
                                    *//*查看*//*
                                    if ("查看".equals(flow_actionBtn.getText())) {
                                        flow_fileBtn.setVisible(true);
                                        System.err.println("查看开始》》》》》《《《《《");
                                        String viewThemeName=  themeObject.getString("name");
                                        globalThemeName=viewThemeName;
                                        Path srcPath=Paths.get("C:","myItz",viewThemeName,viewThemeName);
                                        System.err.println("要查看的主题地址为》》》。"+srcPath.toString());
                                        try {
                                            viewThemePreview(primaryStage,srcPath.toString());

                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                        flow_themeHbox.getChildren().setAll(flow_themeLink, flow_actionBtn,flow_fileBtn);

                                    }
                                    *//*解压*//*
                                    if ("解压".equals(flow_actionBtn.getText())) {
                                        System.err.println("解压开始》》》》》《《《《《");
                                        String unzipThemeName = themeObject.getString("name");
                                        String basePath = "C:" + File.separator + "myItz";
                                        Path unzipSrcPath = Paths.get(basePath, unzipThemeName, unzipThemeName + ".itz");
                                        unZipPath = unzipSrcPath.toString();
                                        unZipDestPath = Paths.get(basePath, unzipThemeName).toString();

                                        processBarStage("解压", primaryStage);
                                        unZipBar unzipTask = new unZipBar();
                                        Thread unzipThread = new Thread(unzipTask);
                                        unzipThread.start();
                                        flow_actionBtn.setText("查看");
                                        flow_themeHbox.getChildren().setAll(flow_themeLink, flow_actionBtn,flow_fileBtn);

                                    }

                                    if ("下载".equals(flow_actionBtn.getText())) {
                                        *//*下载*//*
                                        System.err.println("下载开始》》》》》《《《《《");
                                        downloadThemeName = themeObject.getString("name");
                                   *//* processBarStage("下载", primaryStage);
                                    downloadBar downloadTask = new downloadBar();
                                    Thread downloadThread = new Thread(downloadTask);
                                    downloadThread.start();*//*
                                        HashMap fileMap = new HashMap();
                                        fileMap.put("themeName", downloadThemeName);
                                        try {
                                            Httpmethod.getFileByTheme(fileMap, "UTF-8");
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }

                                        flow_actionBtn.setText("解压");
                                        flow_themeHbox.getChildren().setAll(flow_themeLink, flow_actionBtn,flow_fileBtn);
                                    }


                                });

                                *//*打开本地主题目录*//*
                                flow_fileBtn.setOnAction(themeFileBtn->{
                                    String themeName=  themeObject.getString("name");
                                    String themePath = "C:" + File.separator + "myItz"+File.separator+themeName;
                                    File file = new File(themePath);
                                    try {
                                        Desktop.getDesktop().open(file);
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                });



                                flow_themeVbox.getChildren().addAll(preview, flow_themeHbox);
                                themeFlow.getChildren().addAll(flow_themeVbox);

                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    });
                    tab.closableProperty().set(false);
                    tabPane.getTabs().add(tab);

                }

            } catch (Exception e) {
                e.printStackTrace();
            }

            themeFlow.setHgap(50);
            themeFlow.setVgap(20);
            themeFlow.setPadding(new Insets(0, 20, 20, 20));
            themeFlow.setMinWidth(1150);
            themeFlow.setMaxWidth(1150);
            tabPane.setMaxWidth(1150);
            tabPane.setMinWidth(1150);
            tabPane.setMaxHeight(60);
            tabPane.setMinHeight(60);
*/
        });

        /*打开第一阶段主题工具*/
        themeMenuItem.setOnAction(openOldTool -> {
            try {
                viewThemePreview(primaryStage, null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });


        // 使用rxjava 请求厂商数据
        Observable myjson = Observable.create(emitter -> {
            System.out.println("Observable thread is : " + Thread.currentThread().getName());
            emitter.onNext(Httpmethod.getFactorys());
        }).observeOn(JavaFxScheduler.platform())
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io());

        Observer<String> myView = new Observer<String>() {
            @Override
            public void onSubscribe(Disposable disposable) {

            }

            @Override
            public void onNext(String s) {
                JSONArray jsonArray = JSONArray.fromObject(s);
                System.out.println("当前的线程》" + Thread.currentThread().getName());
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                    System.err.println("获取的厂商名为》》》" + " " + jsonObject.getString("name"));

                    String factoryName = jsonObject.getString("name");
                    Tab tab = new Tab();
                    tab.setText(factoryName);
                    /*请求厂商主题数据*/

                    tab.setOnSelectionChanged(select -> {
                        themeFlow.getChildren().clear();
                        System.out.println("当前选中的厂商是-》" + tab.getText());
                        HashMap map = new HashMap();
                        map.put("factoryName", factoryName);
                        /*更换厂商 清空数据*/

                        /*请求主题数据*/
                        Observable myThemeJson = Observable.create(themeEmitter -> {
                            System.out.println("当前线程->->" + Thread.currentThread().getName());
                            String themeJson = Httpmethod.getThemeByFactory(map, "UTF-8");
                            System.out.println("d当前请求的主题数据为-》" + themeJson);
                            themeEmitter.onNext(themeJson);
                        }).observeOn(JavaFxScheduler.platform())
                                .subscribeOn(Schedulers.io()).unsubscribeOn(Schedulers.io());


                        Observer<String> myThemeView = new Observer<String>() {

                            @Override
                            public void onSubscribe(Disposable disposable) {

                            }

                            @Override
                            public void onNext(String s1) {

                                JSONArray themesJson = JSONArray.fromObject(s1);
                                System.out.println("主题数据为-》" + themesJson);
                                for (int j = 0; j < themesJson.size(); j++) {
                                    VBox flow_themeVbox = new VBox();
                                    flow_themeVbox.setSpacing(10);
                                    HBox flow_themeHbox = new HBox();
                                    flow_themeHbox.setAlignment(Pos.CENTER);
                                    flow_themeHbox.setSpacing(10);
                                    Hyperlink flow_themeLink = new Hyperlink();

                                    JSONObject themeObject = (JSONObject) themesJson.get(j);
                                    //   System.err.println("厂商 主题 预览图为》》》》。" +tab.getText()+ themeObject.getString("name") + " " + themeObject.getString("preview"));

                                    Button flow_actionBtn = new Button();
                                    Button flow_fileBtn = new Button("目录");
                                    /*判断主题状态 按钮显示1.下载 2.解压 3. 显示*/
                                    String themeStatus = judgeThemeStatus(themeObject.getString("name"));
                                    if ("下载".equals(themeStatus)) {
                                        flow_actionBtn.setText("下载");

                                        flow_themeHbox.getChildren().setAll(flow_themeLink, flow_actionBtn);
                                    }
                                    if ("解压".equals(themeStatus)) {
                                        flow_actionBtn.setText("解压");
                                        flow_themeHbox.getChildren().setAll(flow_themeLink, flow_actionBtn, flow_fileBtn);

                                    }
                                    if ("查看".equals(themeStatus)) {
                                        flow_actionBtn.setText("查看");

                                        flow_themeHbox.getChildren().setAll(flow_themeLink, flow_actionBtn, flow_fileBtn);
                                    }

                                    HashMap previewMap = new HashMap();
                                    previewMap.put("themeName", themeObject.getString("name"));
                                    ImageView preview = null;
                                    try {
                                        preview = Httpmethod.getPreviewByTheme(previewMap, "UTF-8");
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                    preview.setFitWidth(180);
                                    preview.setPreserveRatio(true);

                                    /*点击列表项链接，创建新窗口显示详情主题*/

                                    flow_themeLink.setText(themeObject.getString("name"));

                                    flow_themeLink.setOnAction((ActionEvent e) -> {
                                        System.out.println("This link is clicked");
                                        try {
                                            themeDetail(flow_themeLink.getText(), primaryStage);
                                        } catch (Exception e1) {
                                            e1.printStackTrace();
                                        }

                                    });

                                    preview.setOnMouseClicked(clicked -> {
                                        System.out.println("This link is clicked");
                                        try {
                                            themeDetail(flow_themeLink.getText(), primaryStage);
                                        } catch (Exception e1) {
                                            e1.printStackTrace();
                                        }
                                    });


                                    /*操作按钮*/
                                    flow_actionBtn.setOnAction(download -> {
                                        /*查看*/
                                        if ("查看".equals(flow_actionBtn.getText())) {
                                            flow_fileBtn.setVisible(true);
                                            System.err.println("查看开始》》》》》《《《《《");
                                            String viewThemeName = themeObject.getString("name");
                                            globalThemeName = viewThemeName;
                                            Path srcPath = Paths.get("C:", "myItz", viewThemeName, viewThemeName);
                                            System.err.println("要查看的主题地址为》》》。" + srcPath.toString());
                                            try {
                                                viewThemePreview(primaryStage, srcPath.toString());

                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                            flow_themeHbox.getChildren().setAll(flow_themeLink, flow_actionBtn, flow_fileBtn);

                                        }
                                        /*解压*/
                                        if ("解压".equals(flow_actionBtn.getText())) {
                                            System.err.println("解压开始》》》》》《《《《《");
                                            String unzipThemeName = themeObject.getString("name");
                                            String basePath = "C:" + File.separator + "myItz";
                                            Path unzipSrcPath = Paths.get(basePath, unzipThemeName, unzipThemeName + ".itz");
                                            unZipPath = unzipSrcPath.toString();
                                            unZipDestPath = Paths.get(basePath, unzipThemeName).toString();

                                            processBarStage("解压", primaryStage);
                                            unZipBar unzipTask = new unZipBar();
                                            Thread unzipThread = new Thread(unzipTask);
                                            unzipThread.start();
                                            flow_actionBtn.setText("查看");
                                            flow_themeHbox.getChildren().setAll(flow_themeLink, flow_actionBtn, flow_fileBtn);

                                        }

                                        if ("下载".equals(flow_actionBtn.getText())) {
                                            /*下载*/
                                            System.err.println("下载开始》》》》》《《《《《");
                                            downloadThemeName = themeObject.getString("name");
                                   /* processBarStage("下载", primaryStage);
                                    downloadBar downloadTask = new downloadBar();
                                    Thread downloadThread = new Thread(downloadTask);
                                    downloadThread.start();*/
                                            HashMap fileMap = new HashMap();
                                            fileMap.put("themeName", downloadThemeName);
                                            try {
                                                Httpmethod.getFileByTheme(fileMap, "UTF-8");
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }

                                            flow_actionBtn.setText("解压");
                                            flow_themeHbox.getChildren().addAll(flow_themeLink, flow_actionBtn, flow_fileBtn);
                                        }


                                    });

                                    /*打开本地主题目录*/
                                    flow_fileBtn.setOnAction(themeFileBtn -> {
                                        String themeName = themeObject.getString("name");
                                        String themePath = "C:" + File.separator + "myItz" + File.separator + themeName;
                                        File file = new File(themePath);
                                        try {
                                            Desktop.getDesktop().open(file);
                                        } catch (IOException e) {
                                            e.printStackTrace();
                                        }
                                    });


                                    flow_themeVbox.getChildren().addAll(preview, flow_themeHbox);
                                    themeFlow.getChildren().addAll(flow_themeVbox);

                                }
                            }

                            @Override
                            public void onError(Throwable throwable) {

                            }

                            @Override
                            public void onComplete() {

                            }
                        };
                        myThemeJson.subscribe(myThemeView);

                    });
                    tab.closableProperty().set(false);
                    tabPane.getTabs().addAll(tab);

                }
                themeVbox.getChildren().setAll(themeFlow);
                themeScroll.setContent(themeVbox);
                factoryVbox.getChildren().setAll(factory_menuBarTop, tabPane, themeScroll);

            }


            @Override
            public void onError(Throwable throwable) {

            }

            @Override
            public void onComplete() {

            }
        };


        myjson.subscribe(myView);

        themeFlow.setHgap(50);
        themeFlow.setVgap(20);
        themeFlow.setPadding(new Insets(0, 20, 20, 20));
        themeFlow.setMinWidth(1150);
        themeFlow.setMaxWidth(1150);
        tabPane.setMaxWidth(1150);
        tabPane.setMinWidth(1150);
        tabPane.setMaxHeight(60);
        tabPane.setMinHeight(60);

        factoryVbox.getChildren().setAll(factory_menuBarTop, tabPane);
        factoryVbox.setPadding(new Insets(0, 10, 20, 25));

        primaryStage.setTitle("主题预览工具");
        primaryStage.setScene(new Scene(factoryVbox, 1200, 700));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

    public int saveAction(int viewCount) throws Exception {
        try {
            GetPreview tempView = new GetPreview();
            if (viewCount == 1) {
                realDialerPane.getChildren().setAll(tempView.getDialerPane(path, 1));
                openFile = tempView.save(realDialerPane, "preview_contact_0", path);

            } else if (viewCount == 2) {
                realMessagePane.getChildren().setAll(tempView.getMessagePane(path, 1));
                openFile = tempView.save(realMessagePane, "preview_contact_1", path);

            } else if (viewCount == 0) {
                realDeskPane.getChildren().setAll(tempView.getDeskPane(path, 1));
                openFile = tempView.save(realDeskPane, "preview_launcher_0", path);

            } else if (viewCount == 3) {
                realDeskPane.getChildren().setAll(tempView.getDeskPane(path, 1));
                openFile = tempView.save(realDeskPane, "preview_launcher_0", path);

                realDialerPane.getChildren().setAll(tempView.getDialerPane(path, 1));
                openFile = tempView.save(realDialerPane, "preview_contact_0", path);
                realMessagePane.getChildren().setAll(tempView.getMessagePane(path, 1));
                openFile = tempView.save(realMessagePane, "preview_contact_1", path);


            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return saveFlag;
    }



    /*刷新*/

    public void refresh(Stage primaryStage) {
        /*重新加载布局*/
        tabPane.getTabs().clear();
        try {
            System.err.println(Httpmethod.getFactorys());
            String jsonResult = Httpmethod.getFactorys();
            JSONArray jsonArray = JSONArray.fromObject(jsonResult);

            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                System.err.println("获取的厂商名为》》》" + " " + jsonObject.getString("name"));
                String factoryName = jsonObject.getString("name");
                Tab tab = new Tab();
                tab.setText(factoryName);
                tab.setOnSelectionChanged(select -> {
                    HashMap map = new HashMap();
                    map.put("factoryName", tab.getText());
                    try {
                        /*更换厂商 清空表格数据*/
                        //   themesTable.getItems().clear();
                        themeFlow.getChildren().clear();
                        /*请求主题数据*/
                        String themes = Httpmethod.getThemeByFactory(map, "UTF-8");
                        JSONArray themesJson = JSONArray.fromObject(themes);

                        for (int j = 0; j < themesJson.size(); j++) {
                            VBox flow_themeVbox = new VBox();
                            flow_themeVbox.setSpacing(10);
                            HBox flow_themeHbox = new HBox();
                            flow_themeHbox.setAlignment(Pos.CENTER);
                            flow_themeHbox.setSpacing(10);
                            Hyperlink flow_themeLink = new Hyperlink();

                            JSONObject themeObject = (JSONObject) themesJson.get(j);
                            System.err.println("主题为》》》》。" + themeObject.getString("name") + " " + themeObject.getString("preview"));

                            Button flow_actionBtn = new Button();
                            Button flow_fileBtn = new Button("目录");
                            /*判断主题状态 按钮显示1.下载 2.解压 3. 显示*/
                            String themeStatus = judgeThemeStatus(themeObject.getString("name"));
                            if ("下载".equals(themeStatus)) {
                                flow_actionBtn.setText("下载");

                                flow_themeHbox.getChildren().setAll(flow_themeLink, flow_actionBtn);
                            }
                            if ("解压".equals(themeStatus)) {
                                flow_actionBtn.setText("解压");
                                flow_themeHbox.getChildren().setAll(flow_themeLink, flow_actionBtn, flow_fileBtn);

                            }
                            if ("查看".equals(themeStatus)) {
                                flow_actionBtn.setText("查看");

                                flow_themeHbox.getChildren().setAll(flow_themeLink, flow_actionBtn, flow_fileBtn);
                            }

                            HashMap previewMap = new HashMap();
                            previewMap.put("themeName", themeObject.getString("name"));
                            ImageView preview = Httpmethod.getPreviewByTheme(previewMap, "UTF-8");
                            preview.setFitWidth(180);
                            preview.setPreserveRatio(true);

                            /*点击列表项链接，创建新窗口显示详情主题*/

                            flow_themeLink.setText(themeObject.getString("name"));

                            flow_themeLink.setOnAction((ActionEvent e) -> {
                                System.out.println("This link is clicked");
                                try {
                                    themeDetail(flow_themeLink.getText(), primaryStage);
                                } catch (Exception e1) {
                                    e1.printStackTrace();
                                }

                            });

                            preview.setOnMouseClicked(clicked -> {
                                System.out.println("This link is clicked");
                                try {
                                    themeDetail(flow_themeLink.getText(), primaryStage);
                                } catch (Exception e1) {
                                    e1.printStackTrace();
                                }
                            });


                            /*操作按钮*/
                            flow_actionBtn.setOnAction(download -> {
                                /*查看*/
                                if ("查看".equals(flow_actionBtn.getText())) {
                                    flow_fileBtn.setVisible(true);
                                    System.err.println("查看开始》》》》》《《《《《");
                                    String viewThemeName = themeObject.getString("name");
                                    globalThemeName = viewThemeName;
                                    Path srcPath = Paths.get("C:", "myItz", viewThemeName, viewThemeName);
                                    System.err.println("要查看的主题地址为》》》。" + srcPath.toString());
                                    try {
                                        viewThemePreview(primaryStage, srcPath.toString());

                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                    flow_themeHbox.getChildren().setAll(flow_themeLink, flow_actionBtn, flow_fileBtn);

                                }
                                /*解压*/
                                if ("解压".equals(flow_actionBtn.getText())) {
                                    System.err.println("解压开始》》》》》《《《《《");
                                    String unzipThemeName = themeObject.getString("name");
                                    String basePath = "C:" + File.separator + "myItz";
                                    Path unzipSrcPath = Paths.get(basePath, unzipThemeName, unzipThemeName + ".itz");
                                    unZipPath = unzipSrcPath.toString();
                                    unZipDestPath = Paths.get(basePath, unzipThemeName).toString();

                                    processBarStage("解压", primaryStage);
                                    unZipBar unzipTask = new unZipBar();
                                    Thread unzipThread = new Thread(unzipTask);
                                    unzipThread.start();
                                    flow_actionBtn.setText("查看");
                                    flow_themeHbox.getChildren().setAll(flow_themeLink, flow_actionBtn, flow_fileBtn);

                                }

                                if ("下载".equals(flow_actionBtn.getText())) {
                                    /*下载*/
                                    System.err.println("下载开始》》》》》《《《《《");
                                    downloadThemeName = themeObject.getString("name");
                                   /* processBarStage("下载", primaryStage);
                                    downloadBar downloadTask = new downloadBar();
                                    Thread downloadThread = new Thread(downloadTask);
                                    downloadThread.start();*/
                                    HashMap fileMap = new HashMap();
                                    fileMap.put("themeName", downloadThemeName);
                                    try {
                                        Httpmethod.getFileByTheme(fileMap, "UTF-8");
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }

                                    flow_actionBtn.setText("解压");
                                    flow_themeHbox.getChildren().setAll(flow_themeLink, flow_actionBtn, flow_fileBtn);
                                }


                            });

                            /*打开本地主题目录*/
                            flow_fileBtn.setOnAction(themeFileBtn -> {
                                String themeName = themeObject.getString("name");
                                String themePath = "C:" + File.separator + "myItz" + File.separator + themeName;
                                File file = new File(themePath);
                                try {
                                    Desktop.getDesktop().open(file);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            });


                            flow_themeVbox.getChildren().addAll(preview, flow_themeHbox);
                            themeFlow.getChildren().addAll(flow_themeVbox);

                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
                tab.closableProperty().set(false);
                tabPane.getTabs().add(tab);

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        themeFlow.setHgap(50);
        themeFlow.setVgap(20);
        themeFlow.setPadding(new Insets(0, 20, 20, 20));
        themeFlow.setMinWidth(1150);
        themeFlow.setMaxWidth(1150);
        tabPane.setMaxWidth(1150);
        tabPane.setMinWidth(1150);
        tabPane.setMaxHeight(60);
        tabPane.setMinHeight(60);
    }


    int saveFlag = 0;

    /*创建进度条窗口*/
    public void processBarStage(String actionName, Stage parentStage) {
        /*进度条*/
        dialogStage = new Stage();
        dialogStage.initOwner(parentStage);
        progressIndicator = new ProgressIndicator();
        Label label = new Label();
        label.setText(actionName + "中,请耐心等待");
        label.setTextFill(Color.RED);
        // label.setMaxSize(60,60);
        progressIndicator.setProgress(-1F);
        progressIndicator.setMaxSize(100, 100);
        VBox vBox = new VBox();
        vBox.setSpacing(10);
        vBox.setBackground(Background.EMPTY);
        // vBox.getChildren().addAll(label);
        vBox.getChildren().addAll(progressIndicator, label);
        dialogStage.initStyle(StageStyle.UNDECORATED);
        dialogStage.initStyle(StageStyle.TRANSPARENT);
        dialogStage.initModality(Modality.APPLICATION_MODAL);
        Scene scene = new Scene(vBox, 120, 120);
        scene.setFill(null);
        dialogStage.setScene(scene);
        dialogStage.show();
    }

    //压缩进度条2
    class createPro implements Runnable {
        int finishFlag = 0;

        // 窗口父子关系

        // progress bar

        @Override
        public void run() {
            String srcPath = path.toString();
            String prePath = srcPath.substring(0, srcPath.lastIndexOf("\\"));
            String toPath = Paths.get(prePath, "ColorFulTest").toString();
            File toFile = new File(toPath);
            if (!toFile.exists()) {
                toFile.mkdirs();
            }
            try {
                compress(srcPath, toPath);
                finishFlag = 1;
            } catch (IOException e) {
                e.printStackTrace();
            }

            Platform.runLater(() -> {
                if (finishFlag == 1) {
                    Alert alert = new Alert(Alert.AlertType.INFORMATION);
                    alert.setTitle("");
                    alert.setHeaderText("");
                    alert.setContentText("压缩完成");
                    alert.showAndWait();
                    dialogStage.close();

                }
            });


        }


    }

    //解压进度条2
    class unZipBar implements Runnable {
        int unzipFlag = 0;

        // 窗口父子关系

        // progress bar

        @Override
        public void run() {

            try {
                System.err.println("解压源文件路径" + unZipPath + " " + "解压存放路径" + unZipDestPath);
                unZip(unZipPath, unZipDestPath);
                unzipFlag = 1;
            } catch (Exception e) {
                e.printStackTrace();
            }

            Platform.runLater(() -> {
                if (unzipFlag == 1) {
                    Alert alert = new Alert(Alert.AlertType.INFORMATION);
                    alert.setTitle("");
                    alert.setHeaderText("");
                    alert.setContentText("解压完成");
                    alert.showAndWait();
                    dialogStage.close();

                }
            });


        }


    }

    //下载进度条2
    class downloadBar implements Runnable {
        int downloadFlag = 0;

        // 窗口父子关系

        // progress bar

        @Override
        public void run() {

            HashMap fileMap = new HashMap();
            fileMap.put("themeName", downloadThemeName);

            try {
                boolean b = Httpmethod.getFileByTheme(fileMap, "UTF-8");
                if (b) {
                    System.err.println("详情下载成功");
                    downloadFlag = 1;
                }

            } catch (Exception e1) {
                e1.printStackTrace();
            }


            Platform.runLater(() -> {
                if (downloadFlag == 1) {
                    Alert alert = new Alert(Alert.AlertType.INFORMATION);
                    alert.setTitle("");
                    alert.setHeaderText("");
                    alert.setContentText("下载完成");
                    alert.showAndWait();
                    dialogStage.close();

                }
            });


        }


    }

    //加载页面进度条2
    class loadingBar implements Runnable {
        int loadingFlag = 0;

        // 窗口父子关系

        // progress bar

        @Override
        public void run() {

            Platform.runLater(() -> {
                boolean b = false;
                try {
                    b = loading();/*加载三张主题界面*/
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (b) {
                    System.err.println("页面加载完成");
                    loadingFlag = 1;
                }
                if (loadingFlag == 1) {
                  /*  Alert alert = new Alert(Alert.AlertType.INFORMATION);
                    alert.setTitle("");
                    alert.setHeaderText("");
                    alert.setContentText("加载完成");
                    alert.showAndWait();*/
                    dialogStage.close();

                }
            });


        }


    }


    //截图进度条
    class ProcessBar extends JFrame implements Runnable {
        int sleepTime = 50;
        JProgressBar progress; // 进度条
        ProgressIndicator ploading;
        long fileSize = 0;
        ///  IoSession session = null;
        int process = 0;

        public ProcessBar(String str) {
            super(str);

            progress = new JProgressBar(1, 100); // 实例化进度条
            ploading = new ProgressIndicator();
            ploading.setBackground(Background.EMPTY);
            progress.setStringPainted(true);// 描绘文字
            progress.setBackground(java.awt.Color.PINK); // 设置背景色
            this.add(progress);
            this.setBounds(200, 300, 250, 80);
            this.setResizable(false);
        }

        public void setVisible() {
            this.setVisible(true);
        }

        public void run() {
            while (true) {
                for (int i = 0; i < 100; i++) {
                    try {
                        progress.setValue(progress.getValue() + 1); // 随着线程进行，增加进度条值
                        progress.setString(progress.getValue() + "%");
                        Thread.sleep(sleepTime);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                JOptionPane.showMessageDialog(this, "截图完成!");
                this.dispose();
                break;
            }

        }

    }

    //压缩进度条
    class compressProcessBar extends JFrame implements Runnable {
        JProgressBar progress; // 进度条
        ProgressIndicator ploading;
        String newFile = "C:" + File.separator + FileName;
        long fileSize = 0;
        int process = 0;

        BaseTool baseTool = new BaseTool();

        public compressProcessBar(String str) {
            super(str);

            progress = new JProgressBar(1, 100); // 实例化进度条
            ploading = new ProgressIndicator();
            ploading.setBackground(Background.EMPTY);
            progress.setStringPainted(true);// 描绘文字
            progress.setBackground(java.awt.Color.PINK); // 设置背景色
            this.add(progress);
            this.setBounds(200, 300, 250, 50);
            this.setResizable(false);
        }

        public void setVisible() {
            this.setVisible(true);
        }

        @Override
        public void run() {


        }

    }


    //查看详情
    public void createNewStage(int viewCount) throws Exception {

        Stage secondStage = new Stage();
        ScrollPane scrollPane = new ScrollPane();
        Pane previewPane = new Pane();
        GetPreview tempView = new GetPreview();


        if (viewCount == 1) {
            realDialerPane.getChildren().setAll(tempView.getDialerPane(path, 1));
            tempView.save(realDialerPane, "preview_contact_0", path);
            //  Image image=new Image("E:\\"+File.separator+FileName+File.separator + "preview_contact_0.png");
            File testFile = new File(path + File.separator + "preview" + File.separator + "preview_contact_0.png");
            Image image = new Image(testFile.toURI().toURL().toString());
            ImageView imageView = new ImageView(image);
            previewPane.getChildren().setAll(imageView);

        } else if (viewCount == 2) {
            realMessagePane.getChildren().setAll(tempView.getMessagePane(path, 1));
            tempView.save(realMessagePane, "preview_contact_1", path);
            // Image image=new Image("E:\\"+File.separator+FileName + File.separator+"preview_contact_1.png");
            File testFile = new File(path + File.separator + "preview" + File.separator + "preview_contact_1.png");
            Image image = new Image(testFile.toURI().toURL().toString());
            ImageView imageView = new ImageView(image);
            previewPane.getChildren().setAll(imageView);
        } else if (viewCount == 0) {

            realDeskPane.getChildren().setAll(tempView.getDeskPane(path, 1));
            tempView.save(realDeskPane, "preview_launcher_0", path);
            File testFile = new File(path + File.separator + "preview" + File.separator + "preview_launcher_0.png");
            Image image = new Image(testFile.toURI().toURL().toString());
            ImageView imageView = new ImageView(image);
            previewPane.getChildren().setAll(imageView);
        }


        scrollPane.setContent(previewPane);

        Scene secondScene = new Scene(scrollPane, 1150, 600);
        secondStage.setScene(secondScene);
        secondStage.show();


    }


    //压缩文件夹
    public static void zipFile(String src, String dest, boolean isCreateDir) {
        File srcFile = new File(src);

        System.out.println("压缩中..." + dest);
//            dest = buildDestinationZipFilePath(srcFile, dest);
        ZipParameters parameters = new ZipParameters();
        parameters.setIncludeRootFolder(isCreateDir);
        parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);           // 压缩方式
        parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);    // 压缩级别
        ZipFile zipFile = null;
        try {
            zipFile = new ZipFile(dest);
            zipFile.addFolder(srcFile, parameters);
        } catch (ZipException e) {
            e.printStackTrace();
        }
    }

    public void compress(String srcPath, String toPath) throws IOException {
        BaseTool baseTool = new BaseTool();
        File fileGroup = new File(srcPath);
        File[] tempList = fileGroup.listFiles();
        String themeName = fileGroup.getName();
        //   String destPath="C:\\Users\\Administrator\\Desktop\\入职培训手册\\打包\\com.android.BBKClock.zip";

        // zipFile("C:\\Users\\Administrator\\Desktop\\入职培训手册\\自以为是的爱\\com.android.BBKClock",
        // "C:\\Users\\Administrator\\Desktop\\入职培训手册\\打包\\com.android.BBKClock.zip",false);

        for (int j = 0; j < tempList.length; j++) {
            String childName = tempList[j].getName();
            System.err.println("正在处理>>>>>" + childName);
            Path outPath = Paths.get(toPath, themeName, childName);
            Files.createDirectories(outPath.getParent());
            if ("icons".equals(childName) || "launcher".equals(childName) || "preview".equals(childName) || "wallpaper".equals(childName)) {
                baseTool.copyFolder(tempList[j].getPath(), outPath.toString());
            } else if ("description.xml".equals(childName)) {
                System.out.println("description.xml复制了");
                baseTool.copyFile(tempList[j].getPath(), outPath.toString());
            } else {
                zipFile(tempList[j].getPath(), outPath.toString(), false);
            }

        }
        zipFile(Paths.get(toPath, themeName).toString(), Paths.get(toPath, themeName + ".itz").toString(), false);


    }


    /*解压Itz文件*/
    public void unZipFile(String src, String dest) throws ZipException, IOException {


        File file = new File(src);
        String parentPath = file.getParent();
        String baseName = file.getName().substring(0, file.getName().lastIndexOf("."));
        /*复制itz文件到临时目录进行解压*/
        Path tempPath = Paths.get(parentPath, baseName + ".zip");
        Path srcPath = Paths.get(file.getPath());

        System.err.println("复制文件》》》" + srcPath + ">>>> " + tempPath);
        Files.copy(srcPath, tempPath);


        ZipFile zFile = new ZipFile(parentPath + File.separator + baseName + ".zip");
        ProgressMonitor progressMonitor = zFile.getProgressMonitor();

      /*  Thread thread=new Thread(new Runnable() {
            @Override
            public void run() {
                   while(true){
                       System.out.println("解压进度》》》"+progressMonitor.getPercentDone());
                       if(progressMonitor.getPercentDone()>=100){
                           System.out.println("监听完成》》'");
                           break;
                       }
                   }

            }
        });
        thread.start();*/
        zFile.setFileNameCharset("gbk");

        File destFile = new File(parentPath + File.separator + baseName);
        if (!destFile.exists())
            destFile.mkdirs();

        System.err.println("解压中》》请稍后" + "destFile>>" + destFile.getPath());
        if (zFile != null)
            zFile.extractAll(destFile.getPath());
        System.err.println("解压完成》》》");

    /*    String itzName=baseName+".itz";
        File itzFile=new File(path+File.separator+itzName);
        file.renameTo(itzFile);
*/

    }

    public void unZip(String src, String dest) throws ZipException, IOException {
        unZipFile(src, dest);
        File tempFile = new File(src);
        String themeName = tempFile.getName().substring(0, tempFile.getName().lastIndexOf("."));
        File file = new File(tempFile.getParent() + File.separator + themeName);
        //  System.err.println("解压的路径为》》》"+file.getPath());
        File[] fileList = file.listFiles();
        for (int i = 0; i < fileList.length; i++) {

            String childName = fileList[i].getName();
            Path destPath = Paths.get(file.getPath(), childName);
            if ("icons".equals(childName) || "launcher".equals(childName) || "preview".equals(childName)
                    || "wallpaper".equals(childName) || "description.xml".equals(childName)) {
            } else {
                System.err.println("第二遍解压中的路径是》》》" + fileList[i].getPath() + " " + "目的路径是》》" + destPath.toString());
                childUnZip(fileList[i].getPath(), destPath.toString());
            }
        }
        System.err.println("所有文件解压完成");

        String parentPath = tempFile.getParent();
        File tempZipFile = new File(parentPath + File.separator + themeName + ".zip");
        tempZipFile.delete();

    }

    public void childUnZip(String src, String dest) throws ZipException {
        File file = new File(src);
        String baseName = file.getName();
        String zipName = baseName + ".zip";
        String path = file.getParent();
        File zipFile = new File(path + File.separator + zipName);
        file.renameTo(zipFile);
        ZipFile zFile = new ZipFile(zipFile.getPath());

        /*监听解压*/
       /* ProgressMonitor progressMonitor = zFile.getProgressMonitor();
        Thread thread=new Thread(new Runnable() {
            @Override
            public void run() {
                while(true){
                    System.out.println("解压进度》》》"+progressMonitor.getPercentDone());
                    if(progressMonitor.getPercentDone()>=99){
                        System.out.println("监听完成》》'");
                        break;
                    }
                }

            }
        });
        thread.start();*/

        zFile.setFileNameCharset("gbk");
        File destFile = new File(dest);//解压存放目录
        if (!destFile.exists())
            destFile.mkdirs();
        System.err.println("子目录解压中》》请稍后");
        zFile.extractAll(destFile.getPath());
        System.err.println("子目录解压完成》》》");
        zipFile.delete();

    }


    /*加载查看主题界面*/
    public boolean loading() throws Exception {
        previewVbox.getChildren().clear();
        preview_dialerPane.getChildren().setAll(new GetPreview().getDialerPane(path, 3));
        preview_messagePane.getChildren().setAll(new GetPreview().getMessagePane(path, 3));
        preview_deskPane.getChildren().setAll(new GetPreview().getDeskPane(path, 3));
        dialerVbox.getChildren().setAll(preview_dialerPane);
        messageVbox.getChildren().setAll(preview_messagePane);
        deskVbox.getChildren().setAll(preview_deskPane);
        threeHbox.getChildren().setAll(preview_deskPane, preview_dialerPane, preview_messagePane);
        previewVbox.getChildren().setAll(threeHbox);
        return true;
    }

    /*点击图片链接  进入主题详情窗口*/
    public void themeDetail(String themeName, Stage parentStage) throws Exception {

        /*向服务器请求数据*/
        HashMap detailMap = new HashMap();
        detailMap.put("themeName", themeName);

        String detailTheme = Httpmethod.getThemeByName(detailMap, "UTF-8");
        JSONObject detailJson = JSONObject.fromObject(detailTheme);
        System.err.println("要查看详情的主题是》》》。" + detailJson);
        String detailName = detailJson.getString("name");
        String detailFactory = detailJson.getString("factory");
        String detailAuthor = detailJson.getString("author");
        String detailUploader = detailJson.getString("uploader");
        String detaildescription = detailJson.getString("description");
        String detailFile = detailJson.getString("schemeFile");

        // 创建新的stage
        Stage secondStage = new Stage();
        GridPane detailGrid = new GridPane();
        detailGrid.setVgap(20);
        detailGrid.setHgap(5);
        detailGrid.setPadding(new Insets(10, 10, 10, 10));
        //detailGrid.setGridLinesVisible(true);

        Label nameLabel = new Label("主题名：");
        Label name = new Label("");
        name.setUnderline(true);
        name.setText(detailName);

        Label factoryLabel = new Label("厂商名：");
        Label factory = new Label("厂商名");
        factory.setUnderline(true);
        factory.setText(detailFactory);

        Label authorLabel = new Label("作者：");
        Label author = new Label("作者");
        author.setUnderline(true);
        author.setText(detailAuthor);

        Label uploaderLabel = new Label("上传者：");
        Label uploader = new Label("上传者");
        uploader.setText(detailUploader);
        uploader.setUnderline(true);

        Label descriptionLabel = new Label("描述：");
        Text description = new Text();
        description.setText(detaildescription);
        description.setUnderline(true);

        // description.setMaxSize(212, 60);

        Label fileLabel = new Label("主题包：");
        Label fileItz = new Label("主题包");
        fileItz.setUnderline(true);
        fileItz.setText(detailFile.substring(detailFile.lastIndexOf("\\") + 1));

        String themeStatus = judgeThemeStatus(themeName);

        Button detailActionBtn = new Button();
        Button detailFileBtn = new Button("目录");

        if ("下载".equals(themeStatus)) {
            detailActionBtn.setText("下载");
        }
        if ("解压".equals(themeStatus)) {
            detailActionBtn.setText("解压");
        }
        if ("查看".equals(themeStatus)) {
            detailActionBtn.setText("查看");
        }
        /*操作按钮*/
        detailActionBtn.setOnAction(detailDown -> {

            downloadThemeName = name.getText();

            /*查看*/
            if ("查看".equals(detailActionBtn.getText())) {

                System.err.println("查看开始》》》》》《《《《《");
                String viewThemeName = themeName;
                globalThemeName = viewThemeName;
                Path srcPath = Paths.get("C:", "myItz", viewThemeName, viewThemeName);
                System.err.println("要查看的主题地址为》》》。" + srcPath.toString());
                try {
                    viewThemePreview(secondStage, srcPath.toString());

                } catch (Exception e) {
                    e.printStackTrace();
                }
                // detailGrid.add(detailFileBtn, 3, 3);

            }
            /*解压*/
            if ("解压".equals(detailActionBtn.getText())) {
                System.err.println("解压开始》》》》》《《《《《");
                String unzipThemeName = themeName;
                String basePath = "C:" + File.separator + "myItz";
                Path unzipSrcPath = Paths.get(basePath, unzipThemeName, unzipThemeName + ".itz");
                unZipPath = unzipSrcPath.toString();
                unZipDestPath = Paths.get(basePath, unzipThemeName).toString();

                processBarStage("解压", secondStage);
                unZipBar unzipTask = new unZipBar();
                Thread unzipThread = new Thread(unzipTask);
                unzipThread.start();
                detailActionBtn.setText("查看");
                //  detailGrid.add(detailFileBtn, 3, 3);
                refresh(parentStage);

            }

            if ("下载".equals(detailActionBtn.getText())) {
                /*下载*/
                System.err.println("下载开始》》》》》《《《《《");
                downloadThemeName = themeName;
                                   /* processBarStage("下载", primaryStage);
                                    downloadBar downloadTask = new downloadBar();
                                    Thread downloadThread = new Thread(downloadTask);
                                    downloadThread.start();*/
                HashMap fileMap = new HashMap();
                fileMap.put("themeName", downloadThemeName);
                try {
                    Httpmethod.getFileByTheme(fileMap, "UTF-8");
                } catch (Exception e) {
                    e.printStackTrace();
                }

                detailActionBtn.setText("解压");
                detailGrid.add(detailFileBtn, 3, 3);
                refresh(parentStage);
            }

        });
        /*查看目录按钮*/
        detailFileBtn.setOnAction(detailFileButton -> {
            String themePath = "C:" + File.separator + "myItz" + File.separator + themeName;
            File file = new File(themePath);
            try {
                Desktop.getDesktop().open(file);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

        Label previewLabel = new Label("预览图：");

        File myFile = new File("C:" + File.separator + "preview" + File.separator + detailName + File.separator + detailName + ".png");
        System.err.println("预览图的具体地址为>>>>>" + myFile.toString());
        Image detailPreview = new Image(myFile.toURI().toURL().toString());

        ImageView detailView = new ImageView(detailPreview);
        detailView.setFitWidth(360);
        detailView.setPreserveRatio(true);
        detailView.setOnMouseClicked(origin -> {
            Stage originPreviewStage = new Stage();
            ScrollPane originPreviewScroll = new ScrollPane();

            File originPreviewFile = new File("C:" + File.separator + "preview" + File.separator + detailName + File.separator + detailName + ".png");
            //  System.err.println("预览图的具体地址为>>>>>" + myFile.toString());
            try {
                Image originPreviewImage = new Image(originPreviewFile.toURI().toURL().toString());
                ImageView originPreviewView = new ImageView(originPreviewImage);
                Pane originPreviewPane = new Pane();
                originPreviewPane.getChildren().addAll(originPreviewView);
                originPreviewScroll.setContent(originPreviewPane);

                Scene secondScene = new Scene(originPreviewScroll, 1150, 600);
                originPreviewStage.setScene(secondScene);
                originPreviewStage.setTitle("主题预览图");
                originPreviewStage.show();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }

        });

        detailGrid.add(nameLabel, 0, 0);
        detailGrid.add(name, 1, 0);
        detailGrid.add(factoryLabel, 2, 0);
        detailGrid.add(factory, 3, 0);
        detailGrid.add(authorLabel, 0, 1);
        detailGrid.add(author, 1, 1);
        detailGrid.add(uploaderLabel, 2, 1);
        detailGrid.add(uploader, 3, 1);
        detailGrid.add(descriptionLabel, 0, 2);
        detailGrid.add(description, 1, 2, 1, 1);


        detailGrid.add(fileLabel, 0, 3);
        detailGrid.add(fileItz, 1, 3);
        detailGrid.add(detailActionBtn, 2, 3);
        if (!"下载".equals(themeStatus)) {
            detailGrid.add(detailFileBtn, 3, 3);
        }


        detailGrid.add(previewLabel, 0, 4);
        detailGrid.add(detailView, 0, 5, 15, 10);

        detailGrid.setPadding(new Insets(10, 50, 0, 50));
        ScrollPane detailScroll = new ScrollPane();
        detailScroll.setContent(detailGrid);

        Scene secondScene = new Scene(detailScroll, 460, 600);
        secondStage.setTitle("主题详情");
        secondStage.setScene(secondScene);
        secondStage.show();

    }

    /*判断主题状态 ：1.未下载 -》下载
                     2.已下载 未解压 -》解压
                     3.已解压  -》查看
   */
    public String judgeThemeStatus(String themeName) {

        String basePath = "C:" + File.separator + "myItz";
        Path themeItzPath = Paths.get(basePath, themeName, themeName + ".itz");
        File themeItz = new File(themeItzPath.toString());
        if (themeItz.exists()) {  /*itz文件存在*/
            Path themeFilePath = Paths.get(basePath, themeName, themeName);
            File themeFile = new File(themeFilePath.toString());
            if (themeFile.exists()) {/*文件夹存在 已解压*/
                return "查看";
            }
            return "解压";
        }

        return "下载";
    }

    /*查看主题预览图 第一阶段*/
    public void viewThemePreview(Stage parentStage, String srcPath) throws Exception {
        //totalVbox.getChildren().clear();
        totalVbox = new VBox();
       /* previewVbox=new VBox();
        threeHbox=new HBox();
        dialerVbox=new HBox();
        messageVbox=new HBox();
        deskVbox =new VBox();
        threeHbox=new HBox();
        threeHbox=new HBox();
        previewVbox=new VBox();
        actionHbox=new HBox();
        totalVbox=new VBox();*/

        Stage primaryStage = new Stage();

       /* loadingBar autoLoadingTask = new loadingBar();
        Thread autoLoadingThread = new Thread(autoLoadingTask);
        autoLoadingThread.start();*/

        primaryStage.initOwner(parentStage);
        MenuBar menuBarTop = new MenuBar();
        menuBarTop.prefWidthProperty().bind(primaryStage.widthProperty());
        // menuBarTop.setPrefWidth(1000);
        Menu fileMenu = new Menu("文件");
        MenuItem themeMenuItem = new MenuItem("打开本地主题目录");
        MenuItem newMenuItem = new MenuItem("导入");
        MenuItem exitMenuItem = new MenuItem("退出");
        exitMenuItem.setOnAction(actionEvent -> Platform.exit());
        fileMenu.getItems().addAll(themeMenuItem, newMenuItem, new SeparatorMenuItem(), exitMenuItem);

        Menu actionMenu = new Menu("操作");
        //  actionMenu.setStyle("-fx-font-weight: bold");
        MenuItem compressMenuItem = new MenuItem("压缩");
        MenuItem unCompressMenuItem = new MenuItem("解压");
        MenuItem copyMenuItem = new MenuItem("复制");
        // MenuItem unCompressMenuItem = new MenuItem("解压");
        MenuItem saveMenuItem = new MenuItem("截图");
        // MenuItem nextMenuItem = new MenuItem("下一张");
        actionMenu.getItems().addAll(compressMenuItem, unCompressMenuItem, saveMenuItem, copyMenuItem);

        Menu dialerActionMenu = new Menu("拨号盘");
        MenuItem dialerSaveMenuItem = new MenuItem("截图");
        MenuItem dialerDetailMenuItem = new MenuItem("查看详情");
        dialerActionMenu.getItems().addAll(dialerSaveMenuItem, dialerDetailMenuItem);

        Menu messageActionMenu = new Menu("信息");
        MenuItem messageSaveMenuItem = new MenuItem("截图");
        MenuItem messageDetailMenuItem = new MenuItem("查看详情");
        messageActionMenu.getItems().addAll(messageSaveMenuItem, messageDetailMenuItem);


        Menu deskActionMenu = new Menu("桌面");
        MenuItem deskSaveMenuItem = new MenuItem("截图");
        MenuItem deskDetailMenuItem = new MenuItem("查看详情");
        deskActionMenu.getItems().addAll(deskSaveMenuItem, deskDetailMenuItem);


        menuBarTop.getMenus().addAll(fileMenu, actionMenu, deskActionMenu, dialerActionMenu, messageActionMenu);

        HBox buttomHbox = new HBox();
        preview_deskPane.setMaxSize(360, 640);
        preview_dialerPane.setMaxSize(360, 640);
        preview_messagePane.setMaxSize(360, 640);

        ProgressBar progressBar = new ProgressBar(0);

        dialerSaveMenuItem.setOnAction(event -> {
            ProcessBar pb = new ProcessBar("正在截图...");
            // 调用进度条
            pb.setVisible();
            Thread thread = new Thread(pb);
            thread.start();
            try {
                saveAction(1);

                Desktop.getDesktop().open(new File(openFile));

            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        dialerDetailMenuItem.setOnAction(event -> {
            try {
                createNewStage(1);
            } catch (Exception e) {
                e.printStackTrace();
            }


        });

        messageSaveMenuItem.setOnAction(event -> {
            ProcessBar pb = new ProcessBar("正在截图...");
            // 调用进度条
            pb.setVisible();
            Thread thread = new Thread(pb);
            thread.start();
            try {
                saveAction(2);

                Desktop.getDesktop().open(new File(openFile));

            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        messageDetailMenuItem.setOnAction(event -> {
            try {
                createNewStage(2);
            } catch (Exception e) {
                e.printStackTrace();
            }

        });

        deskSaveMenuItem.setOnAction(event -> {
            ProcessBar pb = new ProcessBar("正在截图...");
            // 调用进度条
            pb.setVisible();
            Thread thread = new Thread(pb);
            thread.start();
            try {
                saveAction(0);

                Desktop.getDesktop().open(new File(openFile));


            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        deskDetailMenuItem.setOnAction(event -> {
            try {
                createNewStage(0);
            } catch (Exception e) {
                e.printStackTrace();
            }

        });

        //功能按钮
        saveMenuItem.setOnAction(event -> {
            //createPro(primaryStage);
            ProcessBar pb = new ProcessBar("正在截图...");
            // 调用进度条
            pb.setVisible();
            pb.sleepTime = 200;
            Thread thread = new Thread(pb);
            thread.start();
            try {
                saveAction(3);

                Desktop.getDesktop().open(new File(openFile));


            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        themeMenuItem.setOnAction(theme -> {
            String themePath = "C:" + File.separator + "myItz" + File.separator + globalThemeName;
            File file = new File(themePath);
            try {
                Desktop.getDesktop().open(file);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

        /*导入主题包*/
        newMenuItem.setOnAction(newInput -> {

            viewCount = 0;
            builder = DirectoryChooserBuilder.create();
            builder.title("Hello World");
            cwd = System.getProperty("user.dir");
            file = new File(cwd);
            builder.initialDirectory(file);
            chooser = builder.build();
            File chosenDir = chooser.showDialog(primaryStage);
            if (chosenDir != null) {
                try {
                    path = chosenDir.getPath();
                    System.out.println("当前用户选择的绝对路径为" + " " + path);
                    String temPath = path.substring(path.lastIndexOf("\\") + 1, path.length());
                    System.out.println("主题文件夹名称》》》>>>>'" + temPath);
                    FileName = temPath;
                    //  System.out.println(temPath);
                    //  colorPath = path + File.separator + "com.android.systemui" + File.separator + "theme_values.xml";
                    //   System.out.println("xml目录为" + " " + colorPath);
                    String dialerPath = path + File.separator + "com.android.dialer";
                    String systemuiPath = path + File.separator + "com.android.systemui";
                    String iconsPath = path + File.separator + "icons";
                    String vivoPath = path + File.separator + "vivo";
                    String musicPath = path + File.separator + "com.vivo.dream.music";
                    String clockPath = path + File.separator + "com.vivo.dream.clock";

                    // previewVbox.getChildren().clear();
                    //进度条
                   /* dialogStage = new Stage();
                    dialogStage.initOwner(primaryStage);
                    progressIndicator = new ProgressIndicator();
                    Label label = new Label("页面加载中, 请耐心等待...");

                    label.setTextFill(Color.RED);
                    // label.setMaxSize(60,60);
                    progressIndicator.setProgress(-1F);
                    progressIndicator.setMaxSize(100, 100);
                    VBox vBox = new VBox();
                    vBox.setSpacing(10);
                    vBox.setBackground(Background.EMPTY);
                    // vBox.getChildren().addAll(label);
                    vBox.getChildren().addAll(progressIndicator, label);
                    dialogStage.initStyle(StageStyle.UNDECORATED);
                    dialogStage.initStyle(StageStyle.TRANSPARENT);
                    dialogStage.initModality(Modality.APPLICATION_MODAL);
                    Scene scene = new Scene(vBox, 120, 120);
                    scene.setFill(null);
                    dialogStage.setScene(scene);
                    dialogStage.show();*/

                    processBarStage("载入", primaryStage);
                    loadingBar loadingTask = new loadingBar();
                    Thread loadingThread = new Thread(loadingTask);
                    loadingThread.start();
                    //  loading();
                    //   System.out.println(dialerPath);
                     /*   File fileGroup = new File(chosenDir.getAbsolutePath());
                        tempList = fileGroup.listFiles();
                        int fileCount = tempList.length;
                        if (fileGroup != null) {
                            if (fileCount == 29) {
                                loadingFlag = loading();

                            } else {

                                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                                alert.setTitle("");
                                alert.setHeaderText("");
                                alert.setContentText("主题包格式错误，请重新选择文件夹");
                                alert.showAndWait();
                            }

                        }
*/

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

        });

       /* factoryMenuItem.setOnAction(test->{
            try {
                path=srcPath;
                System.out.println("path>>>>>"+path);
                loading();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });*/

        /*压缩*/
        compressMenuItem.setOnAction(event -> {

         /*   String srcPath = path.toString();
            String prePath = srcPath.substring(0, srcPath.lastIndexOf("\\"));
            String toPath = Paths.get(prePath, "ColorFulTest").toString();
            File toFile = new File(toPath);
            if (!toFile.exists()) {
                toFile.mkdirs();
            }
            try {
                compress(srcPath, toPath);
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("");
                alert.setHeaderText("");
                alert.setContentText("压缩完成");
                alert.showAndWait();
            } catch (IOException e) {
                e.printStackTrace();
            }*/

            dialogStage = new Stage();
            dialogStage.initOwner(primaryStage);
            progressIndicator = new ProgressIndicator();
            Label label = new Label("压缩中, 请稍后...");

            label.setTextFill(Color.RED);
            // label.setMaxSize(60,60);
            progressIndicator.setProgress(-1F);
            progressIndicator.setMaxSize(100, 100);
            VBox vBox = new VBox();
            vBox.setSpacing(10);
            vBox.setBackground(Background.EMPTY);
            // vBox.getChildren().addAll(label);
            vBox.getChildren().addAll(progressIndicator, label);
            dialogStage.initStyle(StageStyle.UNDECORATED);
            dialogStage.initStyle(StageStyle.TRANSPARENT);
            dialogStage.initModality(Modality.APPLICATION_MODAL);
            Scene scene = new Scene(vBox, 120, 120);
            scene.setFill(null);
            dialogStage.setScene(scene);
            dialogStage.show();
            createPro cp = new createPro();
            Thread thread1 = new Thread(cp);
            thread1.start();

        });

        /*解压*/
        unCompressMenuItem.setOnAction(event -> {

            Stage stage = new Stage();
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle("请选择要解压的文件");

            fileChooser.setInitialDirectory(new File("C:" + File.separator + "myItz")
            );

            File unCompressFile = fileChooser.showOpenDialog(stage);
            if (unCompressFile != null) {
                try {
                    String fileName = unCompressFile.getName();
                    String path = unCompressFile.getPath();
                    unZipPath = path;
                    unZipDestPath = unCompressFile.getParent();
                    System.err.println("选择解压的文件路径和名称》》》" + fileName + ">>>" + path);

                    /*进度条*/
                    dialogStage = new Stage();
                    dialogStage.initOwner(primaryStage);
                    progressIndicator = new ProgressIndicator();
                    Label label = new Label("解压中, 请耐心等待...");

                    label.setTextFill(Color.RED);
                    // label.setMaxSize(60,60);
                    progressIndicator.setProgress(-1F);
                    progressIndicator.setMaxSize(100, 100);
                    VBox vBox = new VBox();
                    vBox.setSpacing(10);
                    vBox.setBackground(Background.EMPTY);
                    // vBox.getChildren().addAll(label);
                    vBox.getChildren().addAll(progressIndicator, label);
                    dialogStage.initStyle(StageStyle.UNDECORATED);
                    dialogStage.initStyle(StageStyle.TRANSPARENT);
                    dialogStage.initModality(Modality.APPLICATION_MODAL);
                    Scene scene = new Scene(vBox, 120, 120);
                    scene.setFill(null);
                    dialogStage.setScene(scene);
                    dialogStage.show();

                    unZipBar unzipTask = new unZipBar();
                    Thread unzipThread = new Thread(unzipTask);
                    unzipThread.start();

                    //  unZip(path,unCompressFile.getParent());

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

        });


        previewVbox.setPadding(new Insets(0, 0, 0, 30));
        threeHbox.setSpacing(20);
        dialerVbox.getChildren().setAll(preview_dialerPane);
        messageVbox.getChildren().setAll(preview_messagePane);
        deskVbox.getChildren().setAll(preview_deskPane);
        // threePane.getChildren().setAll(dialerVbox,messageVbox,deskVbox);
        threeHbox.getChildren().setAll(dialerVbox, messageVbox, deskVbox);
        previewVbox.getChildren().setAll(threeHbox);
        actionHbox.getChildren().setAll(menuBarTop);
        totalVbox.setSpacing(10);
        // progressBar.setVisible(false);


        buttomHbox.getChildren().setAll(previewVbox);
        totalVbox.getChildren().setAll(actionHbox, buttomHbox);
        ScrollPane scrollPane = new ScrollPane();
        scrollPane.setContent(totalVbox);

        primaryStage.setTitle("主题预览工具");

        primaryStage.setScene(new Scene(totalVbox, 1200, 700));
        primaryStage.show();

        path = srcPath;
        //  processBarStage("载入",primaryStage);
        if (path != null) {
            loading();
        }


    }

}





